/**
 * @Author: dn-jinmin
 * @File:  gogen
 * @Version: 1.0.0
 * @Date: 2024/4/16
 * @Description:
 */

package gogen

import (
	_ "embed"
	"fmt"
	"strings"

	"github.com/zeromicro/go-zero/tools/goctl/api/spec"
	"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)

//go:embed handle.tpl
var handleTemplate string

//go:embed handlerresp.tpl
var handlerrespTemplate string

func genHandle(dir string, rootPkg string, api *spec.ApiSpec) error {
	// http result
	genFile(fileGenConfig{
		dir:             dir,
		subdir:          handlerDir,
		filename:        "result.go",
		templateName:    "handlerrespTemplate",
		templateFile:    "handlerresp.tpl",
		builtinTemplate: handlerrespTemplate,
		data:            map[string]string{},
	})

	return genFile(fileGenConfig{
		dir:             dir,
		subdir:          fmt.Sprintf("%s/%s", handlerDir, api.Module),
		filename:        "handler.go",
		templateName:    "handleTemplate",
		templateFile:    "handle.tpl",
		builtinTemplate: handleTemplate,
		data: map[string]string{
			"pkgName": api.Module,
			"imports": genHandleImports(rootPkg),
		},
	})
}

func genHandleImports(parentPkg string) string {
	var imports []string
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, pkgHttpxDir)))
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, internal+"svc")))
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, handlerDir)))

	return strings.Join(imports, "\n\t")
}
